package config;

import util.IniHelper;

import java.util.Map;

/**
 * app配置
 * 提供配置访问点
 *
 * @author wyl
 */
public class AppConfig {
    private static final String CONFIG_PATH = "./res/config.ini";

    private static final String OTHER_TITLE = "other";
    private static final String OTHER_FONT_FAMILY = "FontFamily";
    private static final String OTHER_THEME = "Theme";
    private static final String OTHER_LANGUAGE = "Language";

    private static final String SERVER_TITLE = "server";
    private static final String SERVER_WS_PATH = "WS_Path";
    private static final String SERVER_WS_PORT = "WS_Port";

    private static final String JWT_TITLE = "jwt_options";
    private static final String JWT_SECURITY_KEY = "JwtSecurityKey";
    private static final String JWT_EXPIRATION_DAY = "JwtExpirationDay";

    //ws服务器配置
    public static ServerConfig ServerConfig;
    //其他配置
    public static OtherConfig OtherConfig;
    //jwt配置
    public static JwtConfig JwtConfig;

    public static void initConfig() throws Exception {
        Map<String, String> map = IniHelper.readIniFile(CONFIG_PATH);
        String font = map.get(OTHER_FONT_FAMILY);
        String theme = map.get(OTHER_THEME);
        String language = map.get(OTHER_LANGUAGE);
        OtherConfig = new OtherConfig(font, theme, language);
        String ws_path = map.get(SERVER_WS_PATH);
        int ws_port = Integer.parseInt(map.get(SERVER_WS_PORT));
        ServerConfig = new ServerConfig(ws_path, ws_port);
        String jwtSecurityKey = map.get(JWT_SECURITY_KEY);
        long jwtExpirationSeconds = Long.parseLong(map.get(JWT_EXPIRATION_DAY));
        JwtConfig = new JwtConfig(jwtSecurityKey, jwtExpirationSeconds);
    }

    public static void setOtherConfig(OtherConfig config) throws Exception {
        ConfigWatch.setInhibition();
        IniHelper.setIni(CONFIG_PATH, OTHER_TITLE, OTHER_FONT_FAMILY, config.fontFamily);
        IniHelper.setIni(CONFIG_PATH, OTHER_TITLE, OTHER_THEME, config.theme);
        IniHelper.setIni(CONFIG_PATH, OTHER_TITLE, OTHER_LANGUAGE, config.language);
    }

    public static void setServerConfig(ServerConfig config) throws Exception {
        ConfigWatch.setInhibition();
        IniHelper.setIni(CONFIG_PATH, SERVER_TITLE, SERVER_WS_PATH, config.websocketPath);
        IniHelper.setIni(CONFIG_PATH, SERVER_TITLE, SERVER_WS_PORT, String.valueOf(config.port));
    }

    public static void setJwtConfig(JwtConfig config) throws Exception {
        ConfigWatch.setInhibition();
        IniHelper.setIni(CONFIG_PATH, JWT_TITLE, JWT_SECURITY_KEY, config.jwtSecurityKey);
        IniHelper.setIni(CONFIG_PATH, JWT_TITLE, JWT_EXPIRATION_DAY, String.valueOf(config.expDay));
    }


    public synchronized static void reload() {
        try {
            initConfig();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
